package com.yuxi.Filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.yuxi.Entity.PowerRole;
import com.yuxi.Entity.PrisonStructure;
import com.yuxi.Entity.UserInfo;
import com.yuxi.Response.Msg;
import com.yuxi.Service.UserService;
import com.yuxi.spring.jbpm.Util.SpringContextUtils;



/**
 * Servlet Filter implementation class FirstCheckFilter
 */
@WebFilter("/LoginFilter/FirstCheckFilter/*")
public class FirstCheckFilter implements Filter {

    /**
     * Default constructor. 
     */
    public FirstCheckFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest  httprequest=(HttpServletRequest)request;
		HttpSession session=httprequest.getSession();
		UserInfo u=(UserInfo)session.getAttribute("user");
		if(u==null){
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json");
			Msg msg=new Msg(false, "用户未登录", System.currentTimeMillis(), "20001", "登陆过滤");
			response.getWriter().print(new Gson().toJson(msg));
		}else{
			UserService userService=(UserService) SpringContextUtils.getBeanByClass(UserService.class);
			PowerRole powerUser=userService.curLoginUserPowerView(session).getPowerRole();			
			if(!(powerUser.isPrisonAreaFirstCheck()||powerUser.isPrisonFirstCheck())){
				Msg msg=new Msg(false, "用户无此权限", System.currentTimeMillis(), "30001", "权限过滤");
				response.getWriter().print(new Gson().toJson(msg));
			}else{
				chain.doFilter(request, response);
			}
			
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
